from application import app
from flask import request,redirect,g#实现跳转，需要引入统一链接管理器UrlManager
from common.models.User import User #引入User数据表
from common.libs.user.UserService import UserService
from common.libs.UrlManager import UrlManager
#引入正则表达式
import  re
'''
在每一个放在到达controllers之前就已经拦截下来
如果cookie校验失败，那么跳转到登录页面
'''
#设置装饰器，Flask自动识别
@app.before_request
def before_request():
    ignore_urls = app.config['IGNORE_URLS']
    ignore_check_login_urls = app.config['IGNORE_CHECK_LOGIN_URLS']
    path = request.path
    # 如果本身是静态页面则不需要判断
    pattern = re.compile("%s" % "|".join(ignore_check_login_urls))
    if pattern.match(path):
        return

    ##判断是否登录成功
    user_info = check_login()
    g.current_user = None
    if user_info:
        g.current_user = user_info

    # 如果本身是登录页面则不需要判断
    pattern = re.compile("%s" % "|".join(ignore_urls))
    if pattern.match(path):
        return

    if not user_info:
         return  redirect(UrlManager.buildUrl("/user/login"))
    return
'''
判断用户是否已经登录
'''
def check_login():
    cookies = request.cookies
    auth_cookie = cookies[app.config['AUTH_COOKIE_NAME']] if app.config['AUTH_COOKIE_NAME'] in cookies else ""
    '''
    打印auth_cookie，结果显示为:INFO in AuthInterceptors: ????#1
    '''
    if auth_cookie is None:
        return False

    auth_info = auth_cookie.split("#")#第一位为随机校验码，第二位为用户uid

    if len(auth_info) != 2:
        return  False
    '''
    从User表中查找对应uid下的记录
    '''
    try:
         user_info = User.query.filter_by(uid = auth_info[1]).first();
    except Exception:
        return  False

    if user_info == None:
        return  False
    app.logger.info(user_info)

    # 若当前用户已经无效
    if user_info.status != 1:
        return False

    if auth_info[0] != UserService.geneAuthCode(user_info):
        return  False

    return  user_info